﻿using System.Collections.Generic;
using System.Globalization;
using System.ServiceModel;
using System.ServiceProcess;
using System.Threading;
using Sautom.CompositionRoot;
using Sautom.CompositionRoot.AutoMapperConfiguration;
using Sautom.WcfServer.Services;
using CommandService = Sautom.WcfServer.Services.CommandService;

namespace Sautom.WcfServer
{
    public sealed class WindowsHostService : ServiceBase
    {
        #region Hosts
        private ICollection<ServiceHost> _serviceHosts;
        private void Initialize()
        {
            Root.Configure();

            if (_serviceHosts != null)
            {
                foreach (var serviceHost in _serviceHosts)
                {
                    if (serviceHost != null && serviceHost.State == CommunicationState.Opened)
                    {
                        serviceHost.Close();
                    }
                }
            }

            _serviceHosts = new List<ServiceHost>
                                {
                                    new InjectedServiceHost(Root.DependencyResolver, typeof(CommandService)),
                                    new InjectedServiceHost(Root.DependencyResolver, typeof(QueriesService)),
                                    new InjectedServiceHost(Root.DependencyResolver, typeof(FileService)),
                                    new InjectedServiceHost(Root.DependencyResolver, typeof(CommonService)),
                                    new InjectedServiceHost(Root.DependencyResolver, typeof(ReportService)),
                                    new InjectedServiceHost(Root.DependencyResolver, typeof(AuthorizationService)),
                                };
        }
        #endregion

        public WindowsHostService()
        {
            // Name the Windows Service
            ServiceName = "WCFWindowsHostService";
        }

        public static void Main()
        {
            ServiceBase.Run(new WindowsHostService());
        }

        protected override void OnStart(string[] args)
        {
            Initialize();

            foreach (var serviceHost in _serviceHosts)
            {
                serviceHost.Open();
            }


            AutoMapperConfigurator.AddConfiguration(
                new AutoMapperConfig.CommandService(), 
                new AutoMapperConfig.QueryService(),
                new AutoMapperConfig.FileService(),
                new AutoMapperConfig.CommonService(),
                new AutoMapperConfig.ReportService(),
                new AutoMapperConfig.AuthorizationService()
                );

            AutoMapperConfigurator.ConfigureMapping();
        }

        protected override void OnStop()
        {
            foreach (var serviceHost in _serviceHosts)
            {
                serviceHost.Close();
            }
        }
    }
}